﻿using System.Collections.Generic;
using System.Reflection;

namespace Core
{
    public class Binding : Core.Component, IAwake
    {
        public object Source { get; private set; }

        private readonly Dictionary<Component, HashSet<FieldInfo>> dict = new();
        private readonly List<Component> tempList = new();

        public void Awake()
        {
            dict.Clear();
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            foreach (var pair in dict)
            {
                pair.Value.Clear();
            }
            dict.Clear();

            base.Dispose();
        }

        public void Add(Component target, FieldInfo field)
        {
            if (!dict.ContainsKey(target))
            {
                dict[target] = new HashSet<FieldInfo>();
            }
            var hset = dict[target];
            if (hset.Contains(field))
            {
                return;
            }
            hset.Add(field);
        }

        public void Remove(Component target)
        {
            if (!dict.ContainsKey(target))
            {
                return;
            }
            dict[target].Clear();
            dict.Remove(target);
        }


        public void Set(object source)
        {
            Source = source;

            tempList.Clear();

            foreach (var pair1 in dict)
            {
                var target = pair1.Key;
                if (target.IsDisposed)
                {
                    tempList.Add(target);
                    continue;
                }
                foreach (var field in pair1.Value)
                {
                    field.SetValue(target, source);
                }
            }

            foreach (var item in tempList)
            {
                Remove(item);
            }

            tempList.Clear();
        }
    }
}
